﻿/******************************************************************************
 *  Author：       Commscope ITDC Suzhou Web Team 
 *  CreateDate：   21/02/2012 2:26:43 PM
 *
 *
 ******************************************************************************/
using System.Collections.Generic;
using HtmlAgilityPack;

namespace EasyDLL.Net
{
    /// <summary>
    /// 网页解析类，专门用于提取网页中的元素
    /// 下载网页请使用HttpWrapper类
    /// </summary>
    public class HtmlParseWrapper
    {
        /// <summary>
        /// 根据Xpath得到某个节点
        /// </summary>
        /// <param name="html"></param>
        /// <param name="xpath"></param>
        /// <returns></returns>
        public static HtmlNode GetSingleNodeByXpath(string html,string xpath)
        {
            HtmlDocument htmlDocument = new HtmlDocument();
            htmlDocument.LoadHtml(html);
            HtmlNode selectSingleNode = htmlDocument.DocumentNode.SelectSingleNode(xpath);
            return selectSingleNode;
        }

        /// <summary>
        /// 根据Xpath得到多个节点
        /// </summary>
        /// <param name="html"></param>
        /// <param name="xPath"></param>
        /// <returns></returns>
        public static List<HtmlNode> GetNodesByXpath(string html, string xPath)
        {
            List<HtmlNode> resList = new List<HtmlNode>();

            HtmlDocument htmlDocument = new HtmlDocument();
            htmlDocument.LoadHtml(html);
            HtmlNodeCollection htmlNodeCollection = htmlDocument.DocumentNode.SelectNodes(xPath);
            if (htmlNodeCollection != null && htmlNodeCollection.Count > 0)
            {
                foreach (HtmlNode node in htmlNodeCollection)
                {
                    resList.Add(node);
                }
            }
            return resList;
        }

        /// <summary>
        /// 根据标签内的ID得到节点
        /// </summary>
        /// <param name="html"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static HtmlNode GetNodeById(string html, string id)
        {
            HtmlDocument htmlDocument = new HtmlDocument();
            htmlDocument.LoadHtml(html);
            HtmlNode elementbyId = htmlDocument.GetElementbyId(id);
            return elementbyId;
        }

        //public static void test(string html,string xPath)
        //{
        //    HtmlDocument htmlDocument = new HtmlDocument();
        //    htmlDocument.LoadHtml(html);
        //    HtmlNode elementbyId = htmlDocument.DocumentNode.
        //    return elementbyId;
        //}
    }
}
